const sd = require('silly-datetime');
const fs = require('fs');
const path = require('path');

module.exports = {
  schedule: {
    cron: '0 1 0 * * *', // 任务的间隔时间, 
    type: 'worker', // 指定所有的 worker都需要执行
  },
  async task(ctx) {
    // 获取前一天
    let day = sd.format(new Date().valueOf() - 1000 * 60 * 60 * 24, 'YYYYMMDD');
    const FileModel = ctx.model.File;
    const dirPath = path.join(process.cwd(), 'app/public/images/upload/' + day)
    const isExists = await fs.existsSync(dirPath)
    if (isExists) {
      const _data = await fs.readdirSync(dirPath);
      const _files = await FileModel.find().select('link');
      const allimgs = [];
      for (let j = 0; j < _files.length; j++) {
        const _fileSuffix = _files[j].link.split('/').pop();
        allimgs.push(_fileSuffix);
      }
      for (let i = 0; i < _data.length; i++) {
        const _path = _data[i];
        if (allimgs.indexOf(_path) == -1) {
          await fs.unlinkSync( path.join(process.cwd(), '/app/public/images/upload/' + day + '/' + _path));
        }
      }
    }
  },
};